<template>
  <div class="content">
    <img id="match1" :src="require('@/assets/img/match1.png')"/>
    <img id="match2" :src="require('@/assets/img/match2.png')" alt="">
    <div class="button">
      <van-button block @click="onMatch" round type="info">开始匹配</van-button>
    </div>
  </div>
</template>

<script>
import {Toast} from "vant";
import api from "@/api/api";

export default {
  name: "Match",
  data() {
    return {
      show: false,
      isMatch: false
    }
  },
  methods: {
    match() {
      let that=this
      let userId=api.getUserId()
      let ws=new WebSocket("ws://hbt123.xyz:8082/match/"+userId)
      ws.onopen = (evt)=>{console.debug("ws://hbt123.xyz:8082/match/"+userId+"连接成功："+JSON.stringify(evt))}
      ws.onerror = (evt)=>{console.debug("连接错误："+evt)}
      ws.onmessage=(res)=>{
        console.debug("接受到自己或对方发送的聊天信息："+JSON.stringify(res))
        console.debug("接受到自己或对方发送的聊天信息data："+JSON.stringify(res.data))
        let msg=JSON.parse(res.data)
        if (msg.type==='chat'){
          let message={
            direction:userId===msg.from_user_id?2:1,
            id:that.$store.state.chatMsg.length+1,
            content:msg.msg,
            ctime:msg.time
          }
          that.$store.commit("addChatMsg",message)
        }else if (msg.type==='match'){
          that.$store.commit("setWs",ws)
          that.isMatch=true
          api.getRoomInfo(msg.room_id).then(res => {
            if (res) {
              console.debug("getRoomInfo"+JSON.stringify(res))
              //{'1': {user_id:1, avatar: 'a.jpg', nick_name: 'tom'}, '2':{user_id: 2, avatar: 'b.jpg', nick_name: 'john'}}
              var me = {}
              var you = {}
              for(var uid in res){
                if (userId === uid){
                  me = res[uid]
                  that.$store.commit("setMeNickName",me.nick_name)
                  that.$store.commit("setMeAvatar",me.avatar)
                }else {
                  you = res[uid]
                  that.$store.commit("setYouNickName",you.nick_name)
                  that.$store.commit("setYouAvatar",you.avatar)
                }
              }
              console.debug(JSON.stringify(me)+"   ****:****\r  "+JSON.stringify(you))
            }
          })
          that.$store.commit("setRoomId",msg.room_id)
        }
      }
      ws.onclose=(err)=>{
        console.log(err)
        that.isMatch=false
      }
    },
    onMatch() {
      this.match()
      let that = this
      let second = 30;
      this.show = true
      const toast = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: false,
        closeOnClick: true,
        mask: true,
        message: '倒计时 30 秒，点击取消匹配',
        onClose() {
          clearInterval(timer)
          console.debug("阿斯顿：Toast close")
        }
      });
      const timer = setInterval(() => {
        second--;
        if (that.isMatch) {
          clearInterval(timer)
          toast.clear();
          that.$router.push("/chat")
        } else if (second) {
          toast.message = `倒计时 ${second} 秒，点击取消匹配`;
        } else {
          clearInterval(timer);
          // 手动清除 Toast
          toast.clear();
          MiniApp.showToast({title: "未匹配到用户，将为您随机分配一名离线用户",duration:3000})
          setTimeout(() => {
            api.getOutlineUser().then(res => {
              if (res) {
                MiniApp.setStorage({key: "mail",
                  data: {from_user: {user_id: res.user_id, nick_name: res.nick_name}},success(){
                    MiniApp.navigateTo({url:"/mailreply.html"})
                  }})
              }
            })
          },2000)
        }
      }, 1000);
    }
  }
}
</script>

<style scoped>
.button {
  text-align: center;
}

#match1 {
  width: 100%;
  height: 13rem;
  border-radius: 45px;
}

#match2 {
  width: 100%;
  height: 13rem;
}

</style>